import img from "./img/game01.webp"
import Square from "./js/Square";

let gameOption = {
    // 游戏配置
    size: 400,
    img: (() => {
        let image = new Image()
        image.src = img
        return image
    })(),
    grade: 4//4到6之间
}
let squareArr = []
let gamecanvas = null
let ctx = null
let timer = null
let active = {
    event:null
};
//如果存在该事件，那么就会调用
let activeEvent = new Proxy(active,{
    set:function(target,key,value){
        if(value){
            startAnimation()
        }
        return Reflect.set(target,key,value)
    },
    get:function(target,key){
        return target[key]
    }
})
export function setActiveEvent(event) {
    activeEvent.event = event
}
export function activeEventisEmpty() {
    return activeEvent.event === null
}
//如果存在activeEvent就会调用
function startAnimation(){
    requestAnimationFrame(()=>{
        if(activeEvent.event){
            activeEvent.event()
            startAnimation()
        }
    })
}
//当图片加载完成时，会回调fn,之所以这样写，那是因为出现了onload回调函数不调用的问题
function imgLoadOk(fn) {
    if (!gameOption.img.complete) {
        requestAnimationFrame(() => {
            imgLoadOk(fn)
        })
    } else {
        fn()
    }
}

//时间循环
function stratGame() {
    console.log("游戏开始")
    if (timer) {
        clearInterval(timer)
    }
    timer = setInterval(() => {
        ctx.clearRect(0, 0, gameOption.size, gameOption.size)
        for (let i = 0; i < squareArr.length; i++) {
            squareArr[i].draw(ctx,gameOption.img)
        }
    }, 33)
}

export function createGame(gameDom, option = gameOption) {
    gamecanvas = document.createElement("canvas")
    if (option.size < 100) {
        throw new Error("size must be 100 or big!")
    }
    if (option.grade < 4 || option.grade > 6) {
        throw new Error("grade must be 4 to 6!")
    }
    gameOption = option
    ctx = gamecanvas.getContext("2d")
    // 创建游戏面板
    gamecanvas.width = gameOption.size
    gamecanvas.height = gameOption.size
    gamecanvas.style.backgroundColor = "#eee"
    gameDom.appendChild(gamecanvas)
    imgLoadOk(() => {
        gameOption.img.style.width = gameOption.size + 'px'
        gameOption.img.style.height = gameOption.size + 'px'
        init()
        stratGame()
    })
}
//初始化，创建square
export function init() {
    let sWidth = gameOption.img.width / gameOption.grade
    let sHeight = gameOption.img.height / gameOption.grade
    let size = gameOption.size / gameOption.grade
    let id = 1;
    //创建square
    for (let i = 0; i < gameOption.grade; i++) {
        for (let j = 0; j < gameOption.grade; j++) {
            if (i == gameOption.grade - 1 && j == gameOption.grade - 1) {
                continue
            }
            let x = j * size
            let y = i * size
            let square = new Square(size, x, y, {
                sx: j * sWidth,
                sy: i * sHeight,
                sWidth: sWidth,
                sHeight: sHeight
            }, id++)
            squareArr.push(square)
            square.draw(ctx, gameOption.img)
        }
    }
    //为canvas添加点击事件,通过判断点击的位置来触发对应的square的点击事件
    gamecanvas.addEventListener('click', (e) => {
        let x = e.offsetX
        let y = e.offsetY
        let square = getSquare(x, y)
        if (square) {
            if(!getSquare(x+square.size,y) && x+square.size<gameOption.size){
                square.move('right')
            }else if(!getSquare(x-square.size,y) && x-square.size >=0){
                square.move('left')
            }else if(!getSquare(x,y+square.size) && y+square.size<gameOption.size){
                square.move('down')
            }else if(!getSquare(x,y-square.size) && y-square.size >=0){
                square.move('up')
            }
        }
    })
}
//通过x,y坐标来获取square
function getSquare(x, y) {
    for (let i = 0; i < squareArr.length; i++) {
        let square = squareArr[i]
        if (isInSquare(square, x, y)) {
            return square
        }
    }
    return null
}
//判断square是否属于x,y的范围
function isInSquare(square, x, y) {
    let sx = square.x
    let sy = square.y
    let size = square.size
    return x >= sx && x < sx + size && y >= sy && y < sy + size
}
